package com.LeeCode;

import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

/**
 * 两数之和 IV - 输入二叉搜索树
 */

public class Code653 {
    public static void main(String[] args) {
        Integer[] arr = {5, 3, 6, 2, 4, null, 7};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code653().findTarget(root, 8));
    }

    public boolean findTarget(TreeNode root, int k) {
        if (root == null) return false;
        Deque<TreeNode> stack = new LinkedList<>();
        Set<Integer> set = new HashSet<>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            if (set.contains(k - node.val)) return true;
            set.add(node.val);
            node = node.right;
        }
        return false;
    }
}
